package com.xjzd.std.concurrency;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AlternatePrintingWithLock {
    private static final Lock lock = new ReentrantLock();
    private static final Condition condition1 = lock.newCondition();
    private static final Condition condition2 = lock.newCondition();
    private static int number = 1;
    private static boolean toggle = true;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (number <= 100) {
                lock.lock();
                try {
                    if (!toggle) {
                        condition1.awaitUninterruptibly();
                    }
                    if (number <= 100) {
                        System.out.println("Thread 1: " + number++);
                    }
                    toggle = !toggle;
                    condition2.signal();
                } finally {
                    lock.unlock();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            while (number <= 100) {
                lock.lock();
                try {
                    if (toggle) {
                        condition2.awaitUninterruptibly();
                    }
                    if (number <= 100) {
                        System.out.println("Thread 2: " + number++);
                    }
                    toggle = !toggle;
                    condition1.signal();
                } finally {
                    lock.unlock();
                }
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}